/*
 *
 * MISC FUNCTIONS
 *
 **/

function loadInputFieldsEffects () {
    $('input').addClass("idleField");

    $('input').focus(function() {
        $(this).removeClass("idleField").addClass("focusField");
        if (this.value == this.defaultValue){
            this.value = '';
        }
        if(this.value != this.defaultValue){
            this.select();
        }
    });

    $('input').blur(function() {
        $(this).removeClass("focusField").addClass("idleField");
        if ($.trim(this.value == '')){
            this.value = (this.defaultValue ? this.defaultValue : '');
        }
    });
}

function alertSize() {
    var myWidth = 0, myHeight = 0;
    if( typeof( window.innerWidth ) == 'number' ) {
        //Non-IE
        myWidth = window.innerWidth;
        myHeight = window.innerHeight;
    } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
        //IE 6+ in 'standards compliant mode'
        myWidth = document.documentElement.clientWidth;
        myHeight = document.documentElement.clientHeight;
    } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
        //IE 4 compatible
        myWidth = document.body.clientWidth;
        myHeight = document.body.clientHeight;
    }

    if ((myHeight - 400) > 300) {
        //document.getElementById("homeCalendarTable").style.height = myHeight - 310;
        document.getElementById("homeCalendarContainer").style.height = myHeight - 275;
        $('#fullcalendar').fullCalendar('option', 'height', myHeight - 275);

        document.getElementById("homeTabsContainer").style.height = myHeight - 150;

        if (document.getElementById("manageUserAccountsTabContentContainer") != null) {
            document.getElementById("manageUserAccountsTabContentContainer").style.height = myHeight - 225;
        }

        if (document.getElementById("manageResourcesTabContentContainer") != null) {
            document.getElementById("manageResourcesTabContentContainer").style.height = myHeight - 225;
        }

        if (document.getElementById("manageReservationsTabContentContainer") != null) {
            document.getElementById("manageReservationsTabContentContainer").style.height = myHeight - 225;
        }

        if (document.getElementById("editUserAccountMenuContainer") != null) {
            document.getElementById("editUserAccountMenuContainer").style.height = myHeight - 250;
        }
        if (document.getElementById("editUserAccountResultsContainer") != null) {
            document.getElementById("editUserAccountResultsContainer").style.height = myHeight - 250;
        }
        if (document.getElementById("editUserAccountFormContainer") != null) {
            document.getElementById("editUserAccountFormContainer").style.height = myHeight - 250;
        }
        if ($("#editUserAccountResultsContainer .internalBoxBody") != null) {
            $("#editUserAccountResultsContainer .internalBoxBody").css("height", myHeight - 280);
        }

        if (document.getElementById("editResourceMenuContainer") != null) {
            document.getElementById("editResourceMenuContainer").style.height = myHeight - 250;
        }
        if (document.getElementById("editResourceResultsContainer") != null) {
            document.getElementById("editResourceResultsContainer").style.height = myHeight - 250;
        }
        if (document.getElementById("editResourceFormContainer") != null) {
            document.getElementById("editResourceFormContainer").style.height = myHeight - 250;
        }
        if (document.getElementById("addResourceFormContainer") != null) {
            document.getElementById("addResourceFormContainer").style.height = myHeight - 250;
        }

        if (document.getElementById("reservationResourcesListBoxContainer") != null) {
            document.getElementById("reservationResourcesListBoxContainer").style.height = myHeight - 250;
        }

    }

}

function formatDateToMySQLFormat (dateString) {

    if (dateString == "") {
        return "";
    }

    var tempDate = new Date(dateString);

    var year = tempDate.getYear();
    if(year < 1000) {
        year += 1900;
    }

    var day = tempDate.getDate();
    if (day < 10) {
        day = "0" + day;
    }

    return year + "-" + (tempDate.getMonth()+1) + "-" + day;;
}

/*
 *
 * AUTHENTICATE USER (LOGIN)
 *
 **/

function submitAuthenticateUserForm() {
    if (isAuthenticateUserFormValid()) {
        disableAuthenticateUserForm();
        $.ajax({
            type: "POST",
            url: "ajaxAuthenticateUser.php",
            dataType: "json",
            data: "email="+$("#email").val()+"&password="+$("#password").val(),
            success: function(response){
                var respnseJsonObj = response;
                enableAuthenticateUserForm();
                if(respnseJsonObj.success == 1) {
                    $(location).attr("href","home.php");
                } else {
                    $("#authenticateUserFormStatusMessage").addClass("errorMessageBox");
                    $("#authenticateUserFormStatusMessage").text("An error has been detected. Please, verify your information or try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
                enableAuthenticateUserForm();
            }
        });
    }
}

function isAuthenticateUserFormValid () {
    isValid = true;
    if (!isEmailInAuthenticateUserFormValid() && isValid) {
        isValid = false;
    }
    if (!isPasswordInAuthenticateUserFormValid() && isValid) {
        isValid = false;
    }
    return isValid;
}

function isEmailInAuthenticateUserFormValid () {
    var emailPattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(($("#email").val().length == 0) || !emailPattern.test($("#email").val())) {
        $("#email").addClass("errorField");
        $("#emailLabel").addClass("errorLabel");
        return false;
    } else {
        $("#email").removeClass("errorField");
        $("#emailLabel").removeClass("errorLabel");
        return true;
    }
}

function isPasswordInAuthenticateUserFormValid () {
    var passwordPattern = new RegExp("[^A-Za-z0-9 ]");
    if($("#password").val().length == 0 || passwordPattern.test($("#password").val())) {
        $("#password").addClass("errorField");
        $("#passwordLabel").addClass("errorLabel");
        return false;
    } else {
        $("#password").removeClass("errorField");
        $("#passwordLabel").removeClass("errorLabel");
        return true;
    }
}

function resetAuthenticateUserForm () {
    $("#authenticateUserFormStatusMessage").removeClass("errorMessageBox");
    $("#authenticateUserFormStatusMessage").html("Please enter your login and password, in order to access to the system:");
    $("#email").removeClass("errorField");
    $("#emailLabel").removeClass("errorLabel");
    $("#password").removeClass("errorField");
    $("#passwordLabel").removeClass("errorLabel");
}

function disableAuthenticateUserForm () {
    $("body").addClass("waitingCursor");
    $("#email").attr("disabled", "disabled");
    $("#password").attr("disabled", "disabled");
    $("#resetAuthenticateUserButton").attr("disabled", "disabled");
    $("#submitAuthenticateUserButton").attr("disabled", "disabled");
    $("#submitAuthenticateUserButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Login");
}

function enableAuthenticateUserForm () {
    $("body").removeClass("waitingCursor");
    $("#email").attr("disabled", "");
    $("#password").attr("disabled", "");
    $("#resetAuthenticateUserButton").attr("disabled", "");
    $("#submitAuthenticateUserButton").attr("disabled", "");
    $("#submitAuthenticateUserButton").html("Login");
}


/*
 *
 * CREATE NEW ACCOUNT
 *
 **/

function submitCreateNewAccountForm() {
    if (isCreateNewAccountFormValid()) {
        disableCreateNewAccountForm();
        $.ajax({
            type: "POST",
            url: "ajaxCreateNewUserAccount.php",
            data: "newUsername="+$("#newUsername").val()+"&newEmail="+$("#newEmail").val()+"&newPassword="+$("#newPassword").val(),
            success: function(response){
                var respnseJsonObj = jQuery.parseJSON(response);
                enableCreateNewAccountForm();
                if(respnseJsonObj.success == 1) {
                    $(location).attr("href","home.php");
                } else {
                    $("#createNewAccountFormStatusMessage").addClass("errorMessageBox");
                    $("#createNewAccountFormStatusMessage").text("An error has been detected. Please, verify your information or try again later.");
                }
            }
        });
    }
}

function isCreateNewAccountFormValid () {
    isValid = true;
    if (!isUsernameInCreateNewAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isEmailInCreateNewAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isPasswordInCreateNewAccountFormValid() && isValid) {
        isValid = false;
    }
    return isValid;
}

function isUsernameInCreateNewAccountFormValid () {
    var usernamePattern = new RegExp("[^A-Za-z ]");
    if($("#newUsername").val().length == 0 || usernamePattern.test($("#newUsername").val())) {
        $("#newUsername").addClass("errorField");
        $("#newUsernameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#newUsername").removeClass("errorField");
        $("#newUsernameLabel").removeClass("errorLabel");
        return true;
    }
}

function isEmailInCreateNewAccountFormValid () {
    var emailPattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(($("#newEmail").val().length == 0) || !emailPattern.test($("#newEmail").val())) {
        $("#newEmail").addClass("errorField");
        $("#newEmailLabel").addClass("errorLabel");
        return false;
    } else {
        $("#newEmail").removeClass("errorField");
        $("#newEmailLabel").removeClass("errorLabel");
        return true;
    }
}

function isPasswordInCreateNewAccountFormValid () {
    var passwordPattern = new RegExp("[^A-Za-z0-9 ]");
    if($("#newPassword").val().length == 0 || passwordPattern.test($("#newPassword").val())) {
        $("#newPassword").addClass("errorField");
        $("#newPasswordLabel").addClass("errorLabel");
        if($("#newVerificationPassword").val().length == 0) {
            $("#newVerificationPassword").addClass("errorField");
            $("#newVerificationPasswordLabel").addClass("errorLabel");
        }
        return false;
    } else if ($("#newPassword").val() != $("#newVerificationPassword").val()) {
        $("#newPassword").addClass("errorField");
        $("#newPasswordLabel").addClass("errorLabel");
        $("#newVerificationPassword").addClass("errorField");
        $("#newVerificationPasswordLabel").addClass("errorLabel");
        return false;
    } else {
        $("#newPassword").removeClass("errorField");
        $("#newPasswordLabel").removeClass("errorLabel");
        $("#newVerificationPassword").removeClass("errorField");
        $("#newVerificationPasswordLabel").removeClass("errorLabel");
        return true;
    }
}

function resetCreateNewAccountForm () {
    $("#createNewAccountFormStatusMessage").removeClass("errorMessageBox");
    $("#createNewAccountFormStatusMessage").html("Please complete the following required ( <span class=\"requiredFieldIndicator\">*</span> ) information:");
    $("#newUsername").removeClass("errorField");
    $("#newUsernameLabel").removeClass("errorLabel");
    $("#newEmail").removeClass("errorField");
    $("#newEmailLabel").removeClass("errorLabel");
    $("#newPassword").removeClass("errorField");
    $("#newPasswordLabel").removeClass("errorLabel");
    $("#newVerificationPassword").removeClass("errorField");
    $("#newVerificationPasswordLabel").removeClass("errorLabel");
}

function disableCreateNewAccountForm () {
    $("body").addClass("waitingCursor");
    $("#newUsername").attr("disabled", "disabled");
    $("#newEmail").attr("disabled", "disabled");
    $("#newPassword").attr("disabled", "disabled");
    $("#newVerificationPassword").attr("disabled", "disabled");
    $("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitCreateNewAccountButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Create Account");
}

function enableCreateNewAccountForm () {
    $("body").removeClass("waitingCursor");
    $("#newUsername").attr("disabled", "");
    $("#newEmail").attr("disabled", "");
    $("#newPassword").attr("disabled", "");
    $("#newVerificationPassword").attr("disabled", "");
    $("#resetCreateNewAccountButton").attr("disabled", "");
    $("#submitCreateNewAccountButton").attr("disabled", "");
    $("#submitCreateNewAccountButton").html("Create Account");
}

/*
 *
 * MANAGE USER ACCOUNTS
 *
 **/

var lastUserRowContainerFromEditUserAccountFormSelected = "";

function showAllUsers() {
    $.ajax({
        type: "POST",
        url: "ajaxGetAllUserAccounts.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                var userList = "";
                $("#editUserAccountResultsContainer div.internalBoxBody").html("");
                if (response.items.length == 0) {
                    $("#editUserAccountResultsContainer div.internalBoxBody").append("<div style=\"text-align:center;margin-top:20px;\">0 User Accounts Found</div>");
                }
                for (var i = 0; i < response.items.length; i++) {
                    userList = "<div id=\"user" + response.items[i].id + "\" class=\"userRowContainer\"><input type=\"radio\" name=\"users\" id=\"userRadio" + response.items[i].id + "\"><label>" + response.items[i].username + "</label></div>";
                    $("#editUserAccountResultsContainer div.internalBoxBody").append(userList);
                    loadUserRowContainersEffects(response.items[i].id);
                }
                $("#editUserAccountResultsContainer .internalBoxBody p").css("display", "none");
                $("#editUserAccountResultsContainer .internalBoxBody div").css("display", "");
                $("#editUserAccountFormContainer .internalBoxBody div").css("display", "none");
                $("#editUserAccountFormContainer .internalBoxBody p").css("display", "");
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function loadUserRowContainersEffects (userId) {
    $("#user"+userId).click(function() {
        populateEditUserAccountForm(userId);
        if (lastUserRowContainerFromEditUserAccountFormSelected != "") {
            $("#" + lastUserRowContainerFromEditUserAccountFormSelected).removeClass("userRowContainerHighlight");
        }
        $("#user"+userId).addClass("userRowContainerHighlight");
        $("#user"+userId).removeClass("userRowContainerSoftHighlight");
        lastUserRowContainerFromEditUserAccountFormSelected = "user"+userId
        $("#userRadio"+userId).attr("checked", "checked");
    });

    $("#user"+userId).mouseover(function() {
        $("#user"+userId).addClass("userRowContainerSoftHighlight");
    });

    $("#user"+userId).mouseout(function() {
        $("#user"+userId).removeClass("userRowContainerSoftHighlight");
    });
}

function populateEditUserAccountForm (userId) {
    $.ajax({
        type: "POST",
        url: "ajaxGetUserAccount.php",
        dataType: "json",
        data: "userId="+userId,
        success: function(response) {
            if(response.success == 1) {
                var user = response.items[0];
                $("#editUserId").val(user.id);
                $("#editUsername").val(user.username);
                $("#editEmail").val(user.email);
                $("#editPassword").val(user.password);
                $("#editUserType").val(user.type);

                $("#editUserAccountFormContainer .internalBoxBody div").css("display", "");
                $("#editUserAccountFormContainer .internalBoxBody p").css("display", "none");
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function submitEditUserAccountForm () {
    if (isEditUserAccountFormValid()) {
        disableEditUserAccountForm();
        $.ajax({
            type: "POST",
            url: "ajaxEditUserAccount.php",
            dataType: "json",
            data: "editUserId="+$("#editUserId").val()+"&editUsername="+$("#editUsername").val()+"&editEmail="+$("#editEmail").val()+"&editPassword="+$("#editPassword").val()+"&editUserType="+$("#editUserType").val(),
            success: function(response){
                enableEditUserAccountForm();
                if(response.success == 1) {
                    enableEditUserAccountForm();
                    $("#user"+$("#editUserId").val()+" label").html($("#editUsername").val());
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
                enableEditUserAccountForm();
            }
        });
    }
}

function isEditUserAccountFormValid () {
    isValid = true;
    if (!isUsernameInEditUserAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isEmailInEditUserAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isPasswordInEditUserAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isUserTypeEditUserAccountFormValid() && isValid) {
        isValid = false;
    }
    return isValid;
}

function isUsernameInEditUserAccountFormValid () {
    var usernamePattern = new RegExp("[^A-Za-z ]");
    if($("#editUsername").val().length == 0 || usernamePattern.test($("#editUsername").val())) {
        $("#editUsername").addClass("errorField");
        $("#editUsernameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editUsername").removeClass("errorField");
        $("#editUsernameLabel").removeClass("errorLabel");
        return true;
    }
}

function isEmailInEditUserAccountFormValid () {
    var emailPattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(($("#editEmail").val().length == 0) || !emailPattern.test($("#editEmail").val())) {
        $("#editEmail").addClass("errorField");
        $("#editEmailLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editEmail").removeClass("errorField");
        $("#editEmailLabel").removeClass("errorLabel");
        return true;
    }
}

function isPasswordInEditUserAccountFormValid () {
    var passwordPattern = new RegExp("[^A-Za-z0-9 ]");
    if($("#editPassword").val().length == 0 || passwordPattern.test($("#editPassword").val())) {
        $("#editPassword").addClass("errorField");
        $("#editPasswordLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editPassword").removeClass("errorField");
        $("#editPasswordLabel").removeClass("errorLabel");
        return true;
    }
}

function isUserTypeEditUserAccountFormValid () {
    if($("#editUserType").val() == 0) {
        $("#editUserTypeLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editUserTypeLabel").removeClass("errorLabel");
        return true;
    }
}

function deleteUserAccount () {
    if (confirm("Are you sure you want to delete the selected user?")) {
        $.ajax({
            type: "POST",
            url: "ajaxDeleteUserAccount.php",
            dataType: "json",
            data: "userId="+$("#editUserId").val(),
            success: function(response){
                if(response.success == 1) {
                    $("#user"+$("#editUserId").val()).remove();
                    $("#editUserAccountFormContainer .internalBoxBody div").css("display", "none");
                    $("#editUserAccountFormContainer .internalBoxBody p").css("display", "");
                    if ($("#editUserAccountResultsContainer .internalBoxBody #userRowContainer").length == 0) {
                        $("#editUserAccountResultsContainer .internalBoxBody").html("<div style=\"text-align: center; margin-top: 20px;\">0 User Accounts Found</div>");
                    }
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
            }
        });
    }
}

function disableEditUserAccountForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitEditUserAccountFormButton").attr("disabled", "disabled");
    $("#submitEditUserAccountFormButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Save Changes");
}

function enableEditUserAccountForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitEditUserAccountFormButton").attr("disabled", "");
    $("#submitEditUserAccountFormButton").html("Save Changes");
}

/*
 *
 * MANAGE MY USER ACCOUNT
 *
 **/

function populateEditMyUserAccountForm () {
    $.ajax({
        type: "POST",
        url: "ajaxGetUserAccount.php",
        dataType: "json",
        data: "userId="+$("#editMyId").val(),
        success: function(response) {
            if(response.success == 1) {
                var user = response.items[0];
                $("#editMyUsername").val(user.username);
                $("#editMyEmail").val(user.email);
                $("#editMyPassword").val(user.password);
                resetEditMyUserAccountForm();
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function submitEditMyUserAccountForm () {
    if (isEditMyUserAccountFormValid()) {
        disableEditMyUserAccountForm();
        $.ajax({
            type: "POST",
            url: "ajaxEditUserAccount.php",
            dataType: "json",
            data: "editUserId="+$("#editMyId").val()+"&editUsername="+$("#editMyUsername").val()+"&editEmail="+$("#editMyEmail").val()+"&editPassword="+$("#editMyPassword").val()+"&editUserType="+$("#editMyUserType").val(),
            success: function(response){
                enableEditMyUserAccountForm();
                if(response.success == 1) {
                    enableEditMyUserAccountForm();
                    $("#authenticatedUsernameContainer").html($("#editMyUsername").val());
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
                enableEditMyUserAccountForm();
            }
        });
    }
}

function resetEditMyUserAccountForm () {
    $("#editMyUsername").removeClass("errorField");
    $("#editMyUsernameLabel").removeClass("errorLabel");
    $("#editMyEmail").removeClass("errorField");
    $("#editMyEmailLabel").removeClass("errorLabel");
    $("#editMyPassword").removeClass("errorField");
    $("#editMyPasswordLabel").removeClass("errorLabel");
}

function isEditMyUserAccountFormValid () {
    isValid = true;
    if (!isMyUsernameInEditMyUserAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isMyEmailInEditMyUserAccountFormValid() && isValid) {
        isValid = false;
    }
    if (!isMyPasswordInEditMyUserAccountFormValid() && isValid) {
        isValid = false;
    }
    return isValid;
}

function isMyUsernameInEditMyUserAccountFormValid () {
    var usernamePattern = new RegExp("[^A-Za-z ]");
    if($("#editMyUsername").val().length == 0 || usernamePattern.test($("#editMyUsername").val())) {
        $("#editMyUsername").addClass("errorField");
        $("#editMyUsernameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editMyUsername").removeClass("errorField");
        $("#editMyUsernameLabel").removeClass("errorLabel");
        return true;
    }
}

function isMyEmailInEditMyUserAccountFormValid () {
    var emailPattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    if(($("#editMyEmail").val().length == 0) || !emailPattern.test($("#editMyEmail").val())) {
        $("#editMyEmail").addClass("errorField");
        $("#editMyEmailLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editMyEmail").removeClass("errorField");
        $("#editMyEmailLabel").removeClass("errorLabel");
        return true;
    }
}

function isMyPasswordInEditMyUserAccountFormValid () {
    var passwordPattern = new RegExp("[^A-Za-z0-9 ]");
    if($("#editMyPassword").val().length == 0 || passwordPattern.test($("#editMyPassword").val())) {
        $("#editMyPassword").addClass("errorField");
        $("#editMyPasswordLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editMyPassword").removeClass("errorField");
        $("#editMyPasswordLabel").removeClass("errorLabel");
        return true;
    }
}

function deleteMyUserAccount () {
    if (confirm("Are you sure you want to delete your user account?")) {
        $.ajax({
            type: "POST",
            url: "ajaxDeleteUserAccount.php",
            dataType: "json",
            data: "userId="+$("#editMyId").val(),
            success: function(response){
                if(response.success == 1) {
                    alert("Your Account Has Been Removed Successfully!");
                    $(location).attr("href","index.php");
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
            }
        });
    }
}

function disableEditMyUserAccountForm () {
    $("#editMyUsername").attr("disabled", "disabled");
    $("#editMyEmail").attr("disabled", "disabled");
    $("#editMyPassword").attr("disabled", "disabled");
    $("#submitEditMyUserAccountFormButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Save Changes");
}

function enableEditMyUserAccountForm () {
    $("#editMyUsername").attr("disabled", "");
    $("#editMyEmail").attr("disabled", "");
    $("#editMyPassword").attr("disabled", "");
    $("#submitEditMyUserAccountFormButton").html("Save Changes");
}

/*
 *
 * MANAGE RESOURCES
 *
 **/

var lastResourceRowContainerFromEditResourceFormSelected = "";

function showAddResourceForm() {
    $("#editResourceResultsContainer").css("display", "none");
    $("#editResourceFormContainer").css("display", "none");
    $("#addResourceFormContainer").css("display", "");
}

function showAllResources() {
    $("#editResourceResultsContainer").css("display", "");
    $("#editResourceFormContainer").css("display", "");
    $("#addResourceFormContainer").css("display", "none");
    
    $.ajax({
        type: "POST",
        url: "ajaxGetAllResources.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                var resourceList = "";
                
                $("#editResourceResultsContainer div.internalBoxBody").html("");
                if (response.items.length == 0) {
                    $("#editResourceResultsContainer div.internalBoxBody").append("<div style=\"text-align:center;margin-top:20px;\">0 Resources Found</div>");
                }
                
                for (var i = 0; i < response.items.length; i++) {
                    resourceList = "<div id=\"resource" + response.items[i].id + "\" class=\"userRowContainer\"><input type=\"radio\" name=\"resources\" id=\"resourceRadio" + response.items[i].id + "\"><label>" + response.items[i].name + "</label></div>";
                    $("#editResourceResultsContainer div.internalBoxBody").append(resourceList);
                    loadResourceRowContainersEffects(response.items[i].id);
                }
                
                $("#editResourceResultsContainer .internalBoxBody p").css("display", "none");
                $("#editResourceResultsContainer .internalBoxBody div").css("display", "");
                $("#editResourceFormContainer .internalBoxBody div").css("display", "none");
                $("#editResourceFormContainer .internalBoxBody p").css("display", "");
                
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function loadResourceRowContainersEffects (resourceId) {
    $("#resource"+resourceId).click(function() {
        populateEditResourceForm(resourceId);
        if (lastResourceRowContainerFromEditResourceFormSelected != "") {
            $("#" + lastResourceRowContainerFromEditResourceFormSelected).removeClass("userRowContainerHighlight");
        }
        $("#resource"+resourceId).addClass("userRowContainerHighlight");
        $("#resource"+resourceId).removeClass("userRowContainerSoftHighlight");
        lastResourceRowContainerFromEditResourceFormSelected = "resource"+resourceId
        $("#resourceRadio"+resourceId).attr("checked", "checked");
    });

    $("#resource"+resourceId).mouseover(function() {
        $("#resource"+resourceId).addClass("userRowContainerSoftHighlight");
    });

    $("#resource"+resourceId).mouseout(function() {
        $("#resource"+resourceId).removeClass("userRowContainerSoftHighlight");
    });
}

function populateEditResourceForm (resourceId) {
    $.ajax({
        type: "POST",
        url: "ajaxGetResource.php",
        dataType: "json",
        data: "resourceId="+resourceId,
        success: function(response) {
            if(response.success == 1) {
                var resource = response.items[0];
                $("#editResourceId").val(resource.id);
                $("#editResourceName").val(resource.name);
                $("#editResourceDescription").val(resource.description);
                $("#editResourceLocation").val(resource.location);
                $("#editResourceGroupName").val(resource.group);
                $("#editResourceStatusValue").val(resource.status);
                $("#editResourceOwner").val(resource.owner);

                $("#editResourceFormContainer .internalBoxBody div").css("display", "");
                $("#editResourceFormContainer .internalBoxBody p").css("display", "none");
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

//EDIT
function submitEditResourceForm () {
    if (isEditResourceFormValid()) {
        disableEditResourceForm();
        $.ajax({
            type: "POST",
            url: "ajaxEditResource.php",
            dataType: "json",
            data: "editResourceId="+$("#editResourceId").val()+"&editResourceName="+$("#editResourceName").val()+"&editResourceDescription="+$("#editResourceDescription").val()+"&editResourceLocation="+$("#editResourceLocation").val()+"&editResourceGroupName="+$("#editResourceGroupName").val()+"&editResourceStatusValue="+$("#editResourceStatusValue").val()+"&editResourceOwner="+$("#editResourceOwner").val(),
            success: function(response){
                enableEditResourceForm();
                if(response.success == 1) {
                    enableEditResourceForm();
                    resetEditResourceForm();
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
                enableEditResourceForm();
            }
        });
    }
}

function isEditResourceFormValid () {
    isValid = true;
    if (!isResourceNameInEditResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isDescriptionInEditResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isLocationInEditResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isGroupNameInEditResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isOwnerInEditResourceFormValid() && isValid) {
        isValid = false;
    }
    return isValid;
}

function isResourceNameInEditResourceFormValid () {
    var usernamePattern = new RegExp("[^A-Za-z ]");
    if($("#editResourceName").val().length == 0 || usernamePattern.test($("#editResourceName").val())) {
        $("#editResourceName").addClass("errorField");
        $("#editResourceNameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editResourceName").removeClass("errorField");
        $("#editResourceNameLabel").removeClass("errorLabel");
        return true;
    }
}

function isDescriptionInEditResourceFormValid () {
    var pattern = new RegExp("[^A-Za-z0-9 ]");
    if(pattern.test($("#editResourceDescription").val())) {
        $("#editResourceDescription").addClass("errorField");
        $("#editResourceDescriptionLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editResourceDescription").removeClass("errorField");
        $("#editResourceDescriptionLabel").removeClass("errorLabel");
        return true;
    }
}

function isLocationInEditResourceFormValid () {
    var pattern = new RegExp("[^A-Za-z0-9 ]");
    if(pattern.test($("#editResourceLocation").val())) {
        $("#editResourceLocation").addClass("errorField");
        $("#editResourceLocationLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editResourceLocation").removeClass("errorField");
        $("#editResourceLocationLabel").removeClass("errorLabel");
        return true;
    }
}

function isGroupNameInEditResourceFormValid () {
    var pattern = new RegExp("[^A-Za-z0-9 ]");
    if(pattern.test($("#editResourceGroupName").val())) {
        $("#editResourceGroupName").addClass("errorField");
        $("#editResourceGroupNameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editResourceGroupName").removeClass("errorField");
        $("#editResourceGroupNameLabel").removeClass("errorLabel");
        return true;
    }
}

function isOwnerInEditResourceFormValid () {
    if($("#editResourceOwner").val() == 0) {
        $("#editResourceOwnerLabel").addClass("errorLabel");
        return false;
    } else {
        $("#editResourceOwnerLabel").removeClass("errorLabel");
        return true;
    }
}

function disableEditResourceForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitEditResourceFormButton").attr("disabled", "disabled");
    $("#submitEditResourceFormButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Save Changes");
}

function enableEditResourceForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitEditResourceFormButton").attr("disabled", "");
    $("#submitEditResourceFormButton").html("Add Resource");
}

function populateEditResourceOwnerInputField () {
    $.ajax({
        type: "POST",
        url: "ajaxGetAllOwners.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                var ownerFieldOptionList = "<option value=\"0\"></option>";
                for (var i = 0; i < response.items.length; i++) {
                    ownerFieldOptionList +=  "<option value=\""+response.items[i].id+"\">"+response.items[i].username+"</option>";
                }
                $("#editResourceOwner").html(ownerFieldOptionList);
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function resetEditResourceForm () {
    //$("#editResourceName").val("");
    //$("#editResourceDescription").val("");
    //$("#editResourceLocation").val("");
    //$("#editResourceGroupName").val("");
    //$("#editResourceOwner").val("");
    $("#editResourceName").removeClass("errorField");
    $("#editResourceNameLabel").removeClass("errorLabel");
    $("#editResourceDescription").removeClass("errorField");
    $("#editResourceDescriptionLabel").removeClass("errorLabel");
    $("#editResourceLocation").removeClass("errorField");
    $("#editResourceLocationLabel").removeClass("errorLabel");
    $("#editResourceGroupName").removeClass("errorField");
    $("#editResourceGroupNameLabel").removeClass("errorLabel");
    $("#editResourceOwner").removeClass("errorField");
    $("#editResourceOwnerLabel").removeClass("errorLabel");
}

//DELETE
function deleteResource () {
    if (confirm("Are you sure you want to delete the selected resource?")) {
        $.ajax({
            type: "POST",
            url: "ajaxDeleteResource.php",
            dataType: "json",
            data: "resourceId="+$("#editResourceId").val(),
            success: function(response){
                if(response.success == 1) {
                    $("#resource"+$("#editResourceId").val()).remove();
                    $("#editResourceFormContainer .internalBoxBody div").css("display", "none");
                    $("#editResourceFormContainer .internalBoxBody p").css("display", "");
                    if ($("#editResourceResultsContainer .internalBoxBody #userRowContainer").length == 0) {
                        $("#editResourceResultsContainer .internalBoxBody").html("<div style=\"text-align: center; margin-top: 20px;\">0 Resources Found</div>");
                    }
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
            }
        });
    }
}

//ADD
function submitAddResourceForm () {
    if (isAddResourceFormValid()) {
        disableAddResourceForm();
        $.ajax({
            type: "POST",
            url: "ajaxAddResource.php",
            dataType: "json",
            data: "addResourceName="+$("#addResourceName").val()+"&addResourceDescription="+$("#addResourceDescription").val()+"&addResourceLocation="+$("#addResourceLocation").val()+"&addResourceGroupName="+$("#addResourceGroupName").val()+"&addResourceOwner="+$("#addResourceOwner").val(),
            success: function(response){
                enableAddResourceForm();
                if(response.success == 1) {
                    enableAddResourceForm();
                    resetCreateNewAccountForm();
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
                enableAddResourceForm();
            }
        });
    }
}

function isAddResourceFormValid () {
    isValid = true;
    if (!isResourceNameInAddResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isDescriptionInAddResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isLocationInAddResourceFormValid() && isValid) {
        isValid = false;
    }
    if (!isOwnerInAddResourceFormValid() && isValid) {
        isValid = false;
    }
    return isValid;
}

function isResourceNameInAddResourceFormValid () {
    var usernamePattern = new RegExp("[^A-Za-z ]");
    if($("#addResourceName").val().length == 0 || usernamePattern.test($("#addResourceName").val())) {
        $("#addResourceName").addClass("errorField");
        $("#addResourceNameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceName").removeClass("errorField");
        $("#addResourceNameLabel").removeClass("errorLabel");
        return true;
    }
}

function isDescriptionInAddResourceFormValid () {
    var pattern = new RegExp("[^A-Za-z0-9 ]");
    if(pattern.test($("#addResourceDescription").val())) {
        $("#addResourceDescription").addClass("errorField");
        $("#addResourceDescriptionLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceDescription").removeClass("errorField");
        $("#addResourceDescriptionLabel").removeClass("errorLabel");
        return true;
    }
}

function isLocationInAddResourceFormValid () {
    var pattern = new RegExp("[^A-Za-z0-9 ]");
    if(pattern.test($("#addResourceLocation").val())) {
        $("#addResourceLocation").addClass("errorField");
        $("#addResourceLocationLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceLocation").removeClass("errorField");
        $("#addResourceLocationLabel").removeClass("errorLabel");
        return true;
    }
}

function isGroupNameInAddResourceFormValid () {
    var pattern = new RegExp("[^A-Za-z0-9 ]");
    if(pattern.test($("#addResourceGroupName").val())) {
        $("#addResourceGroupName").addClass("errorField");
        $("#addResourceGroupNameLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceGroupName").removeClass("errorField");
        $("#addResourceGroupNameLabel").removeClass("errorLabel");
        return true;
    }
}

function isOwnerInAddResourceFormValid () {
    if($("#addResourceOwner").val() == 0) {
        $("#addResourceOwnerLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceOwnerLabel").removeClass("errorLabel");
        return true;
    }
}

function disableAddResourceForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitAddResourceFormButton").attr("disabled", "disabled");
    $("#submitAddResourceFormButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Add Resource");
}

function enableAddResourceForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#submitAddResourceFormButton").attr("disabled", "");
    $("#submitAddResourceFormButton").html("Add Resource");
}

function populateAddResourceOwnerInputField () {
    $.ajax({
        type: "POST",
        url: "ajaxGetAllOwners.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                var ownerFieldOptionList = "<option value=\"0\"></option>";
                for (var i = 0; i < response.items.length; i++) {
                    ownerFieldOptionList +=  "<option value=\""+response.items[i].id+"\">"+response.items[i].username+"</option>";
                }
                $("#addResourceOwner").html(ownerFieldOptionList);
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function resetCreateNewAccountForm () {
    $("#addResourceName").val("");
    $("#addResourceDescription").val("");
    $("#addResourceLocation").val("");
    $("#addResourceGroupName").val("");
    $("#addResourceOwner").val("");
    $("#addResourceName").removeClass("errorField");
    $("#addResourceNameLabel").removeClass("errorLabel");
    $("#addResourceDescription").removeClass("errorField");
    $("#addResourceDescriptionLabel").removeClass("errorLabel");
    $("#addResourceLocation").removeClass("errorField");
    $("#addResourceLocationLabel").removeClass("errorLabel");
    $("#addResourceGroupName").removeClass("errorField");
    $("#addResourceGroupNameLabel").removeClass("errorLabel");
    $("#addResourceOwner").removeClass("errorField");
    $("#addResourceOwnerLabel").removeClass("errorLabel");
}

/*
 *
 * RESERVATION CALENDAR MANAGEMENT
 *
 **/

var lastReservationResourceRowContainerFromReservationCalendarSelected = "";
var reservationCalendarResourceIdSelected = "";

function loadReservationResourcesListContainer () {
    $.ajax({
        type: "POST",
        url: "ajaxGetAllResources.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                var resourceList = "";

                $("#reservationResourcesListContainer").html("");
                if (response.items.length == 0) {
                    $("#reservationResourcesListContainer").append("<div style=\"text-align:center;margin-top:20px;\">0 Resources Found</div>");
                }

                for (var i = 0; i < response.items.length; i++) {
                    resourceList = "<div id=\"reservationResource" + response.items[i].id + "\" class=\"userRowContainer\"><input type=\"radio\" name=\"reservationResources\" id=\"reservationResourceRadio" + response.items[i].id + "\"><label>" + response.items[i].name + "</label></div>";
                    $("#reservationResourcesListContainer").append(resourceList);
                    loadReservationResourceRowContainerEffects(response.items[i].id);
                }

            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function loadReservationResourceRowContainerEffects (resourceId) {
    $("#reservationResource"+resourceId).click(function() {
        if (lastReservationResourceRowContainerFromReservationCalendarSelected != "") {
            $("#" + lastReservationResourceRowContainerFromReservationCalendarSelected).removeClass("userRowContainerHighlight");
        }
        $("#reservationResource"+resourceId).addClass("userRowContainerHighlight");
        $("#reservationResource"+resourceId).removeClass("userRowContainerSoftHighlight");
        lastReservationResourceRowContainerFromReservationCalendarSelected = "reservationResource"+resourceId
        reservationCalendarResourceIdSelected = resourceId;
        $("#reservationResourceRadio"+resourceId).attr("checked", "checked");
        populateReservationCalendar();
        $("#addResourceReservationId").val(resourceId);
    });

    $("#reservationResource"+resourceId).mouseover(function() {
        $("#reservationResource"+resourceId).addClass("userRowContainerSoftHighlight");
    });

    $("#reservationResource"+resourceId).mouseout(function() {
        $("#reservationResource"+resourceId).removeClass("userRowContainerSoftHighlight");
    });
}

function populateReservationCalendar () {
    $.ajax({
        type: "POST",
        url: "ajaxSetReservationResourceIdSessionVariable.php",
        data: "resourceId="+reservationCalendarResourceIdSelected,
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                $("#fullcalendar").fullCalendar("refetchEvents");
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

//ADD
function submitAddResourceReservationForm () {
    if ($("#addResourceReservationId").val() == 0) {
        alert("Please select a resource.");
        return false;
    }
    if (isAddResourceReservationFormValid()) {
        disableAddResourceReservationForm();
        $.ajax({
            type: "POST",
            url: "ajaxAddReservation.php",
            dataType: "json",
            data: "addResourceReservationId="+$("#addResourceReservationId").val()+"&addResourceReservationStartDate="+formatDateToMySQLFormat($("#addResourceReservationStartDate").val())+"&addResourceReservationEndDate="+formatDateToMySQLFormat($("#addResourceReservationEndDate").val())+"&addResourceReservationReoccurrenceId="+$("#addResourceReservationReoccurrenceId").val()+"&addResourceReservationStopDate="+formatDateToMySQLFormat($("#addResourceReservationStopDate").val()),
            success: function(response){
                enableAddResourceReservationForm();
                if(response.success == 1) {
                    enableAddResourceReservationForm();
                    populateReservationCalendar();
                    closeAddResourceReservationDialog();
                } else {
                    alert("An Error has occurred. Please, try again later.");
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                alert("An Error has occurred. Please, try again later.");
                enableAddResourceReservationForm();
            }
        });
    }
    return true;
}

function isAddResourceReservationFormValid () {
    isValid = true;
    
    if (!isResourceReservationEndDateInAddResourceReservationFormValid() && isValid) {
        isValid = false;
    }
    if (!isResourceReservationStopDateInAddResourceReservationFormValid() && isValid) {
        isValid = false;
    }
    
    return isValid;
}

function isResourceReservationEndDateInAddResourceReservationFormValid () {
    if($("#addResourceReservationEndDate").val() == "") {
        $("#addResourceReservationEndDate").addClass("errorField");
        $("#addResourceReservationEndDateLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceReservationEndDate").removeClass("errorField");
        $("#addResourceReservationEndDateLabel").removeClass("errorLabel");
        return true;
    }
}

function isResourceReservationStopDateInAddResourceReservationFormValid () {
    if(($("#addResourceReservationReoccurrenceId").val() != 0) && ($("#addResourceReservationStopDate").val() == "")) {
        $("#addResourceReservationStopDate").addClass("errorField");
        $("#addResourceReservationStopDateLabel").addClass("errorLabel");
        return false;
    } else {
        $("#addResourceReservationStopDate").removeClass("errorField");
        $("#addResourceReservationStopDateLabel").removeClass("errorLabel");
        return true;
    }
}

function disableAddResourceReservationForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#closeAddResourceReservationFormButton").attr("disabled", "disabled");
    $("#submitAddResourceReservationFormButton").attr("disabled", "disabled");
    $("#submitAddResourceReservationFormButton").html("<img src=\"images/loaders/smallLoader.gif\" width=\"12\" alt=\"smallLoader\"/> Create Reservation");
}

function enableAddResourceReservationForm () {
    //$("body").addClass("waitingCursor");
    //$("#newFirstName").attr("disabled", "disabled");
    //$("#newLastName").attr("disabled", "disabled");
    //$("#newEmail").attr("disabled", "disabled");
    //$("#newPassword").attr("disabled", "disabled");
    //$("#newVerificationPassword").attr("disabled", "disabled");
    //$("#resetCreateNewAccountButton").attr("disabled", "disabled");
    $("#closeAddResourceReservationFormButton").attr("disabled", "");
    $("#submitAddResourceReservationFormButton").attr("disabled", "");
    $("#submitAddResourceReservationFormButton").html("Create Reservation");
}

function closeAddResourceReservationDialog () {
    $("#addResourceReservationFormDialogContainer").dialog('close');
}

function resourceReservationReoccurrenceManagement() {
    if ($("#addResourceReservationReoccurrenceId").val() != 0) {
        if (confirm("Reoccurrent reservations are no defined for reservations with 2 or more days in duration. If you still wants to create a reoccurrent reservation press the 'Ok' button and the system will set the End Date with the same value as the start date. Otherwise, press 'Cancel'.")) {
            $("#addResourceReservationEndDate").val($("#addResourceReservationStartDate").val());
            $("#addResourceReservationStopDate").attr("disabled", false);
	} else {
            $("#addResourceReservationReoccurrenceId").val(0);
            $("#addResourceReservationStopDate").val("");
            $("#addResourceReservationStopDate").attr("disabled", true);
	}
    } else {
        $("#addResourceReservationStopDate").val("");
        $("#addResourceReservationStopDate").attr("disabled", true);
    }

    return true;
}


//DELETE
function submitDeleteResourceReservationForm () {
    $.ajax({
        type: "POST",
        url: "ajaxDeleteReservation.php",
        dataType: "json",
        data: "reservationId="+$("#reservationIdToBeDeleted").val(),
        success: function(response){
            if(response.success == 1) {
                populateReservationCalendar();
                closeDeleteResourceReservationDialog();
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
    return true;
}

function closeDeleteResourceReservationDialog () {
    $("#deleteResourceReservationFormDialogContainer").dialog('close');
}

/*
 *
 * REPORTS MANAGEMENT
 *
 **/

function showResourceUsedByUser () {
    alert("Work In Progress!!");
    return;

    $.ajax({
        type: "POST",
        url: "ajaxGenerateResourceUsedByUser.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                $("#reportArea").html(response.report);
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}

function showResourceUsedByPeriod () {
    $.ajax({
        type: "POST",
        url: "ajaxGenerateResourceUsedByPeriod.php",
        dataType: "json",
        success: function(response) {
            if(response.success == 1) {
                $("#reportArea").html(response.report);
            } else {
                alert("An Error has occurred. Please, try again later.");
            }
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("An Error has occurred. Please, try again later.");
        }
    });
}